Hi,
I am new to arrays and pointers. I am trying to write a simple C program where the user inputs a string of characters. The program has to find the character that repeats itself the most times consecutively in the string. If there are two characters that repeat the same number of times then the program should return the first one only.
I can only use the <stdio.h> library.
---------------------------------------------------------
e.g.
Input:
enter a string: AddCCCddddeeeedddCCA
Output:
the character "d" repeats 4 times
---------------------------------------------------------
What I am thinking of doing is using a pointer to point to each element of the array string one at a time and compare it to the previous character and then increment the counter if it is the same, but I get stuck trying to think how will I count for other characters and how will I determine which count is the highest. Do I need two different counters? Can someone suggest a different/efficient approach to this problem.
---------------------------------------------------------
Here's my attempt so far:
Code:
#include <stdio.h>
int character_repeat(char x, char *y); // x corresponds to str, y corresponds to *ptr
//-------------------------------------------------------------------------------------
int main() {
char str[80], *ptr;
printf("Enter a string (< 80 characters): ");
gets(str);
ptr = str; // points to 1st element in the array string
printf("String: %s \n", str); // prints original string
int character_repeat(char x, char *y);
printf("The character %c repeats %d times", character_repeat(str), count);
return 0;
}
//-------------------------------------------------------------------------------------
int character_repeat(char x, char *y) {
int i = 0, count = 0;
while (*y != '\0') {
if (x[i+1] == x[i])
i++;
count++;
// Need something more or different
}
return count;
}
Any help/suggestions would be great.
Thanks.